<?php

namespace app\service;

use app\models\{
    Bank_bill, Staff, Purchase
};

class SellService
{
    /**
     *
     *采购列表
     **/
    public function purchaseList($p, $s, $where)
    {
        $model = new Purchase();
        $staffModel = new Staff();
        $bankModel = new Bank_bill();

        $list = $model->get_purchase_list($p, $s, $where);
        $size = $model->get_purchase_size($where);

        $staffList = $staffModel->get_all_saleman();
        $purchaseArr = [];
        foreach ($list as $k => $v) {
            $purchaseArr[] = $v['purchase_num'];
        }
        $purchasePay = $bankModel->getPurchaseNumPay($purchaseArr);
        $tmp = [];
        foreach ($purchasePay as $k => $v) {
            if (!isset($tmp[$v['purchase_num']])) {
                $tmp[$v['purchase_num']]['money'] = $v['out_money'] - $v['in_money'];
                $tmp[$v['purchase_num']]['last_modify'] = $v['date'];
            } else {
                $tmp[$v['purchase_num']]['money'] += $v['out_money'] - $v['in_money'];
                if (strtotime($tmp[$v['purchase_num']]['last_modify']) < strtotime($v['date'])) {
                    $tmp[$v['purchase_num']]['last_modify'] = $v['date'];
                }
            }
        }

        //更新最新付款时间
        foreach ($list as $v) {
            if (isset($tmp[$v['purchase_num']])) {
                if ($v['last_modify'] != $tmp[$v['purchase_num']]['last_modify']) {
                    $data = [];
                    $data['last_modify'] = $tmp[$v['purchase_num']]['last_modify'];
                    $model->updateByParam($data,$v['id']);
                }
            }

        }
        return ['size' => $size, 'list' => $list, 'staff' => $staffList, 'purchase' => $tmp];
    }
}
